package neu.edu.cn.fileuploaddownload.Controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;

@Controller
public class FileController {
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile uploadfile, HttpServletRequest request) {
        if (!uploadfile.isEmpty()) {
            // 设置上传文件的保存地址目录
            String dirPath = request.getServletContext().getRealPath("/public/");
//                String dirPath ="D:/devEnvIDEA/IdeaProjects/fileUploadDown/src/main/resources/files/";


            File filePath = new File(dirPath);
            System.out.println("=========dirPath=" + dirPath);
            // 如果保存文件的地址不存在，就先创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            // 获取上传文件的原始名称
            String originalFilename = uploadfile.getOriginalFilename();

            try {
                // 使用MultipartFile接口的方法完成文件上传到指定位置
                uploadfile.transferTo(new File(dirPath + originalFilename));
                request.setAttribute("fileurl", "/public/" + originalFilename);

            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
            return "success";
        } else {
            return "error";
        }
    }

    // 所有类型文件下载管理
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
                                               String filename) throws Exception {
        // 指定要下载的文件根路径
//        String dirPath = "D:/devEnvIDEA/IdeaProjects/fileUploadDown/src/main/resources/files/";
        String dirPath = request.getServletContext().getRealPath("/public/");
        // 创建该文件对象
        File file = new File(dirPath + File.separator + filename);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载方式打开（下载前对文件名进行转码）
        filename = getFilename(request, filename);
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }



    }
    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示，并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+", " ");
            }
        }
        //火狐等其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }


}
